#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static void stackDump(lua_State *L) {
    int i;
    int top = lua_gettop(L);
    for (i = 1; i <= top; i++) {
        int t = lua_type(L, i);
        switch(t) {
        case LUA_TSTRING:
            printf("%s", lua_tostring(L, i));
            break;
        case LUA_TBOOLEAN:
            printf(lua_toboolean(L, i)?"true":"false");
            break;
        case LUA_TNUMBER:
            printf("%g", lua_tonumber(L, i));
            break;
        default:
            printf("%s", lua_typename(L, t));
            break;
        }
        printf(" ");
    }
    printf("\n");
}

int foo(lua_State *L)
{
    const char *par = lua_tostring(L, -1);
    printf("%s\n", par);
    
    lua_pushnumber(L, 100);
    lua_pushnumber(L, 200);
    return 2;
}

int main()
{
    char buff[256];
    int error;
    lua_State *L = lua_open();
    luaL_openlibs(L);
    
    /*while (fgets(buff, sizeof(buff), stdin) != NULL) {
        error = luaL_loadbuffer(L, buff, strlen(buff),
                "line") || lua_pcall(L, 0, 0, 0);
        if (error) {
            fprintf(stderr, "%s", lua_tostring(L, -1));
            lua_pop(L, 1);
        }
    }*/

    lua_register(L, "foo", foo);
    const char *buf = "r1, r2 = foo(\"hello\") print(r1..r2)";
    luaL_loadbuffer(L, buf, strlen(buf), "line") || lua_pcall(L, 0, 0, 0);

    lua_close(L);
    return 0;
}

//int main()
int test()
{
    lua_State *L = lua_open();
    lua_newtable(L);
    lua_newtable(L);
    int t = lua_gettop(L);
    lua_pushvalue(L, -1);
    lua_pushstring(L, "key");
    lua_insert(L, -2); // swap key table
    lua_settable(L, 1);

    lua_getfield(L, 1, "key");
    lua_getfield(L, -1, "key");
    stackDump(L);    
    lua_pop(L, 2);

    lua_pushstring(L, "key");
    lua_pushstring(L, "value");
    lua_settable(L, 2);

    lua_getfield(L, 2, "key");
    //lua_pop(L, 2);
    
    lua_getfield(L, 1, "key");
    lua_getfield(L, -1, "key");
    stackDump(L);    


    return 0;
}

